<?php

namespace ASW\Utility\HttpClient;

/**
 * Class ResponseCookie
 *
 * @package lib\Util\HttpClient
 *
 * @property-read string $key
 * @property-read string $value
 * @property-read string $domain
 * @property-read string $path
 * @property-read string $expires
 * @property-read int $expiresTime
 * @property-read bool $isSecure
 * @property-read bool $isSession
 */
class ResponseCookie
{
    private array $_properties = [
        'key'         => '',
        'value'       => '',
        'domain'      => '',
        'path'        => '/',
        'expires'     => '',
        'expiresTime' => 0,
        'isSecure'    => false,
        'isSession'   => false,
    ];

    public static function fromSetCookieHeaderLine(string $line): self
    {
        // _SS=SID=0905DCB7329966D610CFD3A133B76736; domain=.bing.com; path=/; secure; SameSite=None
        // _EDGE_S=SID=0905DCB7329966D610CFD3A133B76736; path=/; httponly; domain=bing.com
        // MUIDB=20A6F047079D6E581073FF5106B36F99; path=/; httponly; expires=Mon, 23-Aug-2021 08:00:21 GMT

        $instance = new self();

        $nodes = explode(';', $line);
        for ($i = 0; $i < count($nodes); $i++) {
            $node = trim($nodes[$i]);
            if ($i === 0) {
                [$key, $value] = explode('=', $node);
                $instance->_properties['key']   = $key;
                $instance->_properties['value'] = $value;
            } elseif ($node === 'httponly') {
                $instance->_properties['isSession'] = true;
            } elseif ($node === 'secure') {
                $instance->_properties['isSecure'] = true;
            } elseif (str_starts_with($node, 'domain=')) {
                $instance->_properties['domain'] = substr($node, 7);
            } elseif (str_starts_with($node, 'path=')) {
                $instance->_properties['path'] = substr($node, 5);
            } elseif (str_starts_with($node, 'expires=')) {
                $timeString                           = substr($node, 8);
                $instance->_properties['expires']     = $timeString;
                $instance->_properties['expiresTime'] = strtotime($timeString);
            }
        }

        return $instance;
    }

    public function __get(string $propertyName)
    {
        if (!array_key_exists($propertyName, $this->_properties)) return null;

        return $this->_properties[$propertyName];
    }
}